<?php

namespace BoojasrFramework\Service;

use Doctrine\ORM\EntityManager;
use Doctrine\ORM\ORMSetup;

class DoctrineManageService
{
    private $entityPaths=[];
    private $defaultConnection=null;
    private $connections=[];
    private $isDevMode=false;

    /** @var EntityManager[]  */
    private $entityManages=[];

    /**
     * @return array
     */
    public function getEntityPaths()
    {
        return $this->entityPaths;
    }

    /**
     * @param array $entityPath
     */
    public function setEntityPaths($entityPaths): void
    {
        $this->entityPaths = $entityPaths;
    }

    /**
     * @return string
     */
    public function getDefaultConnection()
    {
        return $this->defaultConnection;
    }

    /**
     * @param string $defaultConnection
     */
    public function setDefaultConnection($defaultConnection): void
    {
        $this->defaultConnection = $defaultConnection;
    }

    /**
     * @return array
     */
    public function getConnections()
    {
        return $this->connections;
    }

    /**
     * @param array $connections
     */
    public function setConnections($connections): void
    {
        $this->connections = $connections;
    }

    /**
     * @return bool
     */
    public function isDevMode(): bool
    {
        return $this->isDevMode;
    }

    /**
     * @param bool $isDevMode
     */
    public function setIsDevMode(bool $isDevMode): void
    {
        $this->isDevMode = $isDevMode;
    }

    /**
     * @param $name
     * @return EntityManager
     * @throws \Doctrine\ORM\Exception\ORMException
     */
    public function getEntityManage($name="main")
    {
        if (isset($this->entityManages[$name])){
            return $this->entityManages[$name];
        }
        $config = ORMSetup::createAnnotationMetadataConfiguration($this->getEntityPaths(), $this->isDevMode);
        $connections = $this->getConnections();
        if (!isset($connections[$name])){
            return null;
        }
        $dbParams = $connections[$name];
        $entityManager = EntityManager::create($dbParams, $config);
        $this->setEntityManage($name,$entityManager);
        return $entityManager;
    }

    /**
     * @param $name
     * @param $entityManage
     * @return $this
     */
    public function setEntityManage($name,$entityManage){
        $this->entityManages[$name] = $entityManage;

        return $this;
    }

    /**
     * @return EntityManager[]
     */
    public function getEntityManages(): array
    {
        return $this->entityManages;
    }

    /**
     * @param EntityManager[] $entityManages
     */
    public function setEntityManages(array $entityManages): void
    {
        $this->entityManages = $entityManages;
    }

}